package com.sosee.cgfw.gaodemap;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.amap.api.maps.AMap;
import com.amap.api.maps.MapView;
import com.amap.api.navi.AMapNavi;
import com.amap.api.navi.AMapNaviListener;
import com.amap.api.navi.model.AMapNaviInfo;
import com.amap.api.navi.model.AMapNaviLocation;
import com.amap.api.navi.model.AMapNaviPath;
import com.amap.api.navi.model.NaviInfo;
import com.amap.api.navi.model.NaviLatLng;
import com.amap.api.navi.view.RouteOverLay;
import com.amap.api.services.core.LatLonPoint;
import com.amap.api.services.route.BusRouteResult;
import com.amap.api.services.route.DrivePath;
import com.amap.api.services.route.DriveRouteResult;
import com.amap.api.services.route.RouteSearch;
import com.amap.api.services.route.WalkPath;
import com.amap.api.services.route.WalkRouteResult;
import com.sosee.cgfw.R;
import com.sosee.cgfw.gaodemap.util.Utils;
import com.sosee.cgfw.utils.Constans;
import com.sosee.cgfw.utils.LogUtils;

import java.util.ArrayList;

/**
 * 路径规划页面
 * */
public class SimpleNaviRouteActivity extends Activity implements
		OnClickListener, AMapNaviListener, RouteSearch.OnRouteSearchListener {
	// 起点、终点坐标显示
	private TextView mStartPointTextView;
	private TextView mEndPointTextView;
	// 驾车线路：路线规划、模拟导航、实时导航按钮
	private Button mDriveRouteButton;
	private Button mDriveEmulatorButton;
	private ImageView mDriveNaviButton;
	// 步行线路：路线规划、模拟导航、实时导航按钮
	private Button mFootRouteButton;
	private Button mFootEmulatorButton;
	private Button mFootNaviButton;
	// 地图和导航资源
	private MapView mMapView;
	private AMap mAMap;
	private AMapNavi mAMapNavi;

	// 起点终点坐标
	private NaviLatLng mNaviStart = new NaviLatLng(39.989614, 116.481763);
	private NaviLatLng mNaviEnd = com.sosee.cgfw.utils.Utils.eNlat;
	// 起点终点列表
	private ArrayList<NaviLatLng> mStartPoints = new ArrayList<NaviLatLng>();
	private ArrayList<NaviLatLng> mEndPoints = new ArrayList<NaviLatLng>();
	// 规划线路
	private RouteOverLay mRouteOverLay;
	// 是否驾车和是否计算成功的标志
	private boolean mIsDriveMode = true;
	private boolean mIsCalculateRouteSuccess = false;
	private TextView tv_lujing;//显示路径详情
	private TextView tv_money;//收费信息



	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_simple_route);
		initView(savedInstanceState);
		MainApplication.getInstance().addActivity(this);
	}
	// 初始化View
	private void initView(Bundle savedInstanceState) {

		tv_lujing= (TextView) findViewById(R.id.tv_lujing);
		tv_money= (TextView) findViewById(R.id.tv_money);


		mAMapNavi = AMapNavi.getInstance(this);
		mAMapNavi.setAMapNaviListener(this);
//		mStartPoints.clear();
//		mEndPoints.clear();
		mStartPoints.add(mNaviStart);
		mEndPoints.add(mNaviEnd);
		mDriveNaviButton = (ImageView) findViewById(R.id.car_navi_navi);
		mDriveNaviButton.setOnClickListener(this);
		mMapView = (MapView) findViewById(R.id.simple_route_map);
		mMapView.onCreate(savedInstanceState);
		mAMap = mMapView.getMap();
		mRouteOverLay = new RouteOverLay(mAMap, null);

		mIsCalculateRouteSuccess = false;
		mIsDriveMode = true;
		beginCaculate();
//		testMethod();

	}
	//待测试方法
	public void testMethod(){
		calculateDriveRoute();
		mStartPoints.clear();
		NaviLatLng mSt=new NaviLatLng(getIntent().getDoubleExtra("lat",0),getIntent().getDoubleExtra("long",0));
		mStartPoints.add(mSt);
		initRouteSearch();
		testRouteSearch(true);
	}
	//开始路劲规划
	public void beginCaculate(){
		int flag=getIntent().getIntExtra("flag",0);
		NaviLatLng mSt=new NaviLatLng(getIntent().getDoubleExtra("lat",0),getIntent().getDoubleExtra("long",0));
		LogUtils.log_E("begin suan lu"+flag);
//		if(flag==0){
//			calculateDriveRoute();
//			mStartPoints.clear();
//			mStartPoints.add(mSt);
//			initRouteSearch();
//			testRouteSearch(true);
//		}else{
//			calculateFootRoute();
//			mStartPoints.clear();
//			mStartPoints.add(mSt);
//			initRouteSearch();
//			testRouteSearch(false);
//		}
		switch (flag){
			case Constans.JIACHE_MONE:
				drivingMode=RouteSearch.DrivingSaveMoney;
				calculateDriveRoute();
				mStartPoints.clear();
				mStartPoints.add(mSt);
				initRouteSearch();
				testRouteSearch(true);
				break;
			case Constans.JIACHE_FAST:
				drivingMode=RouteSearch.DrivingDefault;
				calculateDriveRoute();
				mStartPoints.clear();
				mStartPoints.add(mSt);
				initRouteSearch();
				testRouteSearch(true);
				break;
			case Constans.JIACHE_YONGDU:
				drivingMode=RouteSearch.DrivingShortDistance;
				calculateDriveRoute();
				mStartPoints.clear();
				mStartPoints.add(mSt);
				initRouteSearch();
				testRouteSearch(true);
				break;
			case Constans.BUXING:
				calculateFootRoute();
				mStartPoints.clear();
				mStartPoints.add(mSt);
				initRouteSearch();
				testRouteSearch(false);
				break;
		}

	}

	//计算驾车路线
	private void calculateDriveRoute() {
		NaviLatLng mSt=new NaviLatLng(getIntent().getDoubleExtra("lat",0),getIntent().getDoubleExtra("long",0));
		mStartPoints.clear();
		mStartPoints.add(mSt);
		boolean isSuccess=mAMapNavi.calculateDriveRoute(mStartPoints,mEndPoints, null, AMapNavi.DrivingDefault);
		if (!isSuccess) {
			showToast("路线计算失败,检查参数情况");
		}

	}
	//计算步行路线
	private void calculateFootRoute() {
		NaviLatLng mSt=new NaviLatLng(getIntent().getDoubleExtra("lat",0),getIntent().getDoubleExtra("long",0));
		boolean isSuccess = mAMapNavi.calculateWalkRoute(mSt,mNaviEnd);
		if (!isSuccess) {
			showToast("路线计算失败,检查参数情况");
		}
	}

	private void showToast(String message) {
		Toast.makeText(this, message, Toast.LENGTH_SHORT).show();
	}

	private void startGPSNavi(boolean isDrive) {
		if ((isDrive && mIsDriveMode && mIsCalculateRouteSuccess)
				|| (!isDrive && !mIsDriveMode && mIsCalculateRouteSuccess)) {
			Intent gpsIntent = new Intent(SimpleNaviRouteActivity.this,
					SimpleNaviActivity.class);
			Bundle bundle = new Bundle();
			bundle.putBoolean(Utils.ISEMULATOR, false);
			bundle.putInt(Utils.ACTIVITYINDEX, Utils.SIMPLEGPSNAVI);
			gpsIntent.putExtras(bundle);
			gpsIntent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
			startActivity(gpsIntent);
		} else {
			showToast("请先进行相对应的路径规划，再进行导航");
		}
	}
//-------------------------Button点击事件和返回键监听事件---------------------------------
	@Override
	public void onClick(View v) {
		startGPSNavi(true);

//		switch (v.getId()) {
//		case R.id.car_navi_route:
//			mIsCalculateRouteSuccess = false;
//			mIsDriveMode = true;
//			calculateDriveRoute();
//			break;
//		case R.id.car_navi_emulator:
//			startEmulatorNavi(true);
//			break;
//		case R.id.car_navi_navi:
//			startGPSNavi(true);
//			break;
//		case R.id.foot_navi_route:
//			mIsCalculateRouteSuccess = false;
//			mIsDriveMode = false;
//			calculateFootRoute();
//			break;
//		case R.id.foot_navi_emulator:
//			startEmulatorNavi(false);
//			break;
//		case R.id.foot_navi_navi:
//			startGPSNavi(false);
//			break;
//
//		}

	}
	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {

		if (keyCode == KeyEvent.KEYCODE_BACK) {
//			Intent intent = new Intent(SimpleNaviRouteActivity.this,
//					MainStartActivity.class);
//			intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
//			startActivity(intent);
			finish();
			MainApplication.getInstance().deleteActivity(this);

		}
		return super.onKeyDown(keyCode, event);
	}
	
	//--------------------导航监听回调事件-----------------------------
	@Override
	public void onArriveDestination() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onArrivedWayPoint(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onCalculateRouteFailure(int arg0) {
		showToast("路径规划出错" + arg0);
		mIsCalculateRouteSuccess = false;
	}

	@Override
	public void onCalculateRouteSuccess() {
		AMapNaviPath naviPath = mAMapNavi.getNaviPath();
		if (naviPath == null) {
			return;
		}
		// 获取路径规划线路，显示到地图上
		mRouteOverLay.setRouteInfo(naviPath);
		mRouteOverLay.addToMap();
		mIsCalculateRouteSuccess = true;
	}





	private int drivingMode = RouteSearch.DrivingDefault;// 驾车默认模式
	private RouteSearch routeSearch;

	public void initRouteSearch(){
		routeSearch = new RouteSearch(this);
		routeSearch.setRouteSearchListener(this);
	}
	public void testRouteSearch(boolean isDriver){
		LatLonPoint sLat=new LatLonPoint(mStartPoints.get(0).getLatitude(),mStartPoints.get(0).getLongitude());
		LatLonPoint eLat=new LatLonPoint(mEndPoints.get(0).getLatitude(),mEndPoints.get(0).getLongitude());
		RouteSearch.FromAndTo fromAndTo=new RouteSearch.FromAndTo(sLat,eLat);
		if(isDriver){
			RouteSearch.DriveRouteQuery query = new RouteSearch.DriveRouteQuery(fromAndTo, drivingMode,
					null, null, "");// 第一个参数表示路径规划的起点和终点，第二个参数表示驾车模式，第三个参数表示途经点，第四个参数表示避让区域，第五个参数表示避让道路
			routeSearch.calculateDriveRouteAsyn(query);// 异步路径规划驾车模式查询
		}else{
			RouteSearch.WalkRouteQuery wQuery=new RouteSearch.WalkRouteQuery(fromAndTo,0);
			routeSearch.calculateWalkRouteAsyn(wQuery);
		}

	}
































	@Override
	public void onEndEmulatorNavi() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGetNavigationText(int arg0, String arg1) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onGpsOpenStatus(boolean arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviFailure() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onInitNaviSuccess() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onLocationChange(AMapNaviLocation arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onNaviInfoUpdated(AMapNaviInfo arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForTrafficJam() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onReCalculateRouteForYaw() {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartNavi(int arg0) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onTrafficStatusUpdate() {
		// TODO Auto-generated method stub

	}

//------------------生命周期重写函数---------------------------	

	@Override
	public void onResume() {
		super.onResume();
		mMapView.onResume();

	}

	@Override
	public void onPause() {
		super.onPause();
		mMapView.onPause();

	}

	@Override
	public void onDestroy() {
		super.onDestroy();
		mMapView.onDestroy();
		//删除监听 
		AMapNavi.getInstance(this).removeAMapNaviListener(this);
	 
	}

	@Override
	public void onNaviInfoUpdate(NaviInfo arg0) {
		  
		// TODO Auto-generated method stub  
		
	}

	private DriveRouteResult driveRouteResult;// 驾车模式查询结果
	@Override
	public void onBusRouteSearched(BusRouteResult busRouteResult, int i) {

	}

	@Override
	public void onDriveRouteSearched(DriveRouteResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				driveRouteResult = result;
				DrivePath drivePath = driveRouteResult.getPaths().get(0);
				float distance=drivePath.getDistance();
				long time=drivePath.getDuration();
//				Toast.makeText(this,"共"+money+"元"+";共"+distance/1000+"公里"+"；预计耗时："+time,Toast.LENGTH_SHORT).show();
				tv_lujing.setText("全程："+distance/1000+"公里"+"/"+time/60+"分钟");
				tv_money.setText("收费："+drivePath.getTolls()+"元");
			} else {

			}
		} else if (rCode == 27) {
//			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
//			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
//			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
//					+ rCode);
		}
	}
	private WalkRouteResult walkRouteResult;
	@Override
	public void onWalkRouteSearched(WalkRouteResult result, int rCode) {
		if (rCode == 0) {
			if (result != null && result.getPaths() != null
					&& result.getPaths().size() > 0) {
				walkRouteResult = result;
				WalkPath walkPath = walkRouteResult.getPaths().get(0);
				float distance=walkPath.getDistance();
				long time=walkPath.getDuration();
//				Toast.makeText(this,"共"+money+"元"+";共"+distance/1000+"公里"+"；预计耗时："+time,Toast.LENGTH_SHORT).show();
				tv_lujing.setText("全程："+distance/1000+"公里"+"/"+time/60+"分钟");
//				tv_money.setText("收费："+walkPath.getTolls()+"元");




//				mAMap.clear();// 清理地图上的所有覆盖物
//				WalkRouteOverlay walkRouteOverlay = new WalkRouteOverlay(this,
//						mAMap, walkPath, walkRouteResult.getStartPos(),
//						walkRouteResult.getTargetPos());
//				walkRouteOverlay.removeFromMap();
//				walkRouteOverlay.addToMap();
//				walkRouteOverlay.zoomToSpan();


			} else {
//				ToastUtil.show(RouteActivity.this, R.string.no_result);
			}
		} else if (rCode == 27) {
//			ToastUtil.show(RouteActivity.this, R.string.error_network);
		} else if (rCode == 32) {
//			ToastUtil.show(RouteActivity.this, R.string.error_key);
		} else {
//			ToastUtil.show(RouteActivity.this, getString(R.string.error_other)
//					+ rCode);
		}

	}

	public void backM(View view){
		finish();
	}

	@Override
	public void onBackPressed() {
		finish();
	}
}
